(function() {
	$.isPhone = function() {
		//return true;
		var sUserAgent = navigator.userAgent.toLowerCase();
		var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
		var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
		var bIsMidp = sUserAgent.match(/midp/i) == "midp";
		var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
		var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
		var bIsAndroid = sUserAgent.match(/android/i) == "android";
		var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
		var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";

		if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
			return true;
		} else {
			return false;
		}
	}
})(jQuery);
(function() {
	$.fn.plugbase = function(name, settings, params) {
		if (typeof settings == "string") {
			if ($.fn[name] && $.fn[name].methods[settings]) {
				return $.fn[name].methods[settings](this, params);
			} else if ($.fn.plugmethods[settings]) {
				return $.fn.plugmethods[settings](this, params);
			}
		}
		if ($.fn.plugmethods[name]) {
			return $.fn.plugmethods[name](this, settings);
		} else {
			if (!$.fn[name]) return;
			settings = settings || {};
			return $(this).each(function() {
				var options = $(this).data("options");
				if (!options) {
					///将插件基类默认配置、插件默认配置与实际配置合并
					options = $.extend({}, $.fn.plugdefaults, $.fn[name].defaults, settings);
					///将配置参数寄存于dom上
					$(this).data("options", options);
					///设置背景样式
					$(this).css(options["background-css"]);
					///设置模块样式名
					if (options.cls) {
						$(this).addClass(options.cls);
					}
					///初始化插件
					$(this)[name]("_init");
					options.oninit.call(this);
				}
			});
		}
	};
	$.fn.plugdefaults = {
		oninit: function() {}, //初始化后回调
		cls: "", //样式名
		isaudio: !0, //是否播放音乐，默认认是
		autoplay: !1, //是否自动播放 ，默认否	
		"background-css": {} //背景样式
	};
	$.fn.plugmethods = {

		_init: function() {},
		options: function(dom) {
			return $(dom).data("options");
		},
		playaudio: function(dom, name) {
			return $(dom).each(function() {
				var $audio = $(this).find("audio");
				var options = $(this).plugbase("options");
				if (options.isaudio) {
					if ($audio.length == 0) { //检测播放器是否存在
						$audio = $("<audio>");
						$("<div>", {
							css: {
								display: "none"
							}
						}).append($audio).appendTo($(this));
					}
					if ($audio.length > 0) {
						var src = options[name]; //获取音频配置地址
						if (src) {
							$audio[0].pause();
							$audio[0].src = src;
							$audio[0].play(); //播放声音
						}
					}
				}
			});
		}
	};
})(jQuery);

///动画元素
function animate(settings) {
	settings = settings || {};
	var that = this;
	for (var item in settings) {
		that[item] = settings[item];
	}
	if (!this.render) this.render = function() {};
}
animate.prototype.init = function() {
	var dom = this.render();
	var name = this["animation-name"];
	var duration = this["animation-duration"];
	var delay = this["animation-delay"];
	if (name) {
		dom.css({
			"animation-name": name,
			"-webkit-animation-name": name,
			"-moz-animation-name": name,
			"-o-animation-name": name
		});
	}
	if (duration) {
		dom.css({
			"animation-duration": duration,
			"-webkit-animation-duration": duration,
			"-moz-animation-duration": duration,
			"-o-animation-duration": duration
		});
	}
	if (delay) {
		dom.css({
			"animation-delay": delay,
			"-webkit-animation-delay": delay,
			"-moz-animation-delay": delay,
			"-o-animation-delay": delay
		});
	}
};

///星级评价
function evaluate_star(settings) {
	settings = settings || {};
	this.title = settings.title || ""; //提示语
	this.result = settings.result || 0; //星级结果
	this.buttons = settings.buttons || [];
	this.onrender = settings.onredner || function() {};
}
evaluate_star.prototype.render = function() {
	var star = this.star;
	var $star = $("<div>", {
		"class": "star_result"
	});
	var $body = $("<div>", {
		'class': "star_result_body"
	});
	$star.append($body);
	if (this.title) {
		$body.append("<div class='star_result_title'>" + this.title + "</div>")
	}
	var $stars = $("<div>", {
		'class': "star_result_stars"
	});
	for (var i = 0; i < this.result; i++) {
		$stars.append("<span class='star'/>");
	}
	$body.append($stars);
	if (this.buttons) {
		var $action = $("<div>", {
			'class': "star_result_action"
		});
		for (var i = 0; i < this.buttons.length; i++) {
			var ibutton = $("<a>", {
				href: 'javascript:void(0);',
				'class': this.buttons[i].cls || ""
			}).text(this.buttons[i].caption);
			if (this.buttons[i].callback) {
				ibutton.bind("click", callback);
			}
			$action.append(ibutton);
		}
		$body.append($action);
	}
	this.onrender($star);
	return $star;
};
//找朋友插件
(function() {
	$.fn.findfriend = function(settings, param) {
		return $(this).plugbase("findfriend", settings, param);
	};
	$.fn.findfriend.defaults = {
		title: "找朋友", //标题
		style: "", //装饰图片
		data: [], //数据
		animation: {
			name: "fadeInDown", //动画效果名称
			duration: "0.6s", //动画执行时间			
			spacing: "0.2" //间隔时间
		},
		prompt: "", //说明
		istimer: !0, //是否显示记时，默认是
		istimes: !0, //是否显示记录移动步数，默认是
		render_audio: "img/start.mp3", //渲染时播放的声音
		right_audio: "img/right.mp3", //正确时播放的声音,
		wrong_audio: "img/wrong.mp3", //错误时播放的声音,
		success_audio: "img/success.mp3", //成功完成时播放的声音
		over_audio: "img/over.mp3", //移动经过时播放的声音
		onswitch: function(drag, target) {}, //当交换时回调
		onover: function(time, steep) {}, //当结束时回调
		onstart: function() {} //当开始时回调
	};
	$.fn.findfriend.methods = $.extend({}, $.fn.plugmethods, {
		_init: function(jq) {
			var $jq = $(jq);
			var options = $jq.findfriend("options");
			if (options.title) {
				$jq.append("<h2>" + options.title + "</h2>")
			}
			if (options.style || options.istimer || options.istimes) {
				var $style = $("<div>", {
					'class': 'style'
				});
				if (options.style) {
					if (typeof options.style == "string") {
						$style.append("<img src='" + options.style + "'/>");
					} else if (typeof options.style == "object") {
						options.style.render = function() {
							var $img = $("<img>", {
								src: options.style.src
							});
							$style.append($img);
							return $img;
						};
						options.style.init();
					}
				}
				if (options.istimer || options.istimes) {
					var $statistics = $("<div>", {
						'class': 'statistics'
					});
					if (options.istimer) {
						$statistics.append("<span>用时：<em class='time'>0</em>秒");
					}
					if (options.istimes) {
						$statistics.append("<span>移动：<em class='steep'>0</em>步");
					}
					$style.append($statistics);
				};
				$jq.append($style);
			}
			var data = options.data;
			if (data && data.length > 0) {
				var $main = $("<div>", {
					'class': "main"
				});
				$jq.append($main);
			}
			if (!options.autoplay) {
				$jq.append('<div class="action"><a href="javascript:void(0);" class="start">开始</a>	</div>');
			}
			if (options.prompt) {
				$jq.append('<div class="prompt"><h3>操作提示：</h3><p>' + options.prompt + '</p></div>')
			}
			if (options.autoplay) {
				$jq.findfriend("start");
			} else {
				$jq.find(".start").bind("click", function() {
					$jq.find(".action a").html("重新开始");
					if ($(this).data("started")) {
						$jq.findfriend("_render");
					}
					$(this).data("started", true);
					$jq.findfriend("start");

				});
			}
			$jq.findfriend("_render");
		},
		_render: function(jq) {
			$(jq).each(function() {
				var options = $(this).findfriend("options");
				options.time = 0;
				options.right = 0;
				options.steep = 0;
				options.started = false;
				$(this).find(".time").html(options.time);
				$(this).find(".steep").html(options.steep);
				var random1 = [];
				var random2 = [];
				var r = [];
				var r2 = [];
				var data = options.data;
				options.total = data.length;
				for (var i = 0; i < data.length; i++) {
					r.push(i);
				}
				random1 = r.concat();
				random1.sort(function() {
					return 0.5 - Math.random();
				});
				random2 = r.concat();
				random2.sort(function() {
					return 0.5 - Math.random();
				});
				//获取第二级随机排序数，检测是否与第一组有相同的，如果有再取
				function getRandom2() {
					var has = false;
					for (var i = 0; i < random1.length; i++) {
						if (random1[i] == random2[i]) {
							has = true;
							break;
						}
					}
					if (has) {
						random2 = r.concat();
						random2.sort(function() {
							return 0.5 - Math.random();
						});
						getRandom2();
					}
				}
				getRandom2();
				var that = this;
				var $jq = $(this);
				var $main = $(this).find(".main");
				$main.empty();
				for (var i = 0; i < random1.length; i++) {
					var $letter = $("<div>", {
						'class': 'letter-con'
					});
					$letter.html('<div class="pinyin" data-index="' + random1[i] + '"><span>' + data[random1[i]].py + '</span></div>' +
						'<div class="hanzi"  draggable=true data-index="' + random2[i] + '"><span>' + data[random2[i]].hanzi + '</span></div>');

					//当设置的动画效果，并且有间隔时间时，分别设置动画效果
					if (options.animation && options.animation.spacing != 0) {
						if (options.animation.name) {
							$letter.css({
								"animation-name": options.animation.name,
								"-webkit-animation-name": options.animation.name,
								"-moz-animation-name": options.animation.name,
								"-o-animation-name": options.animation.name
							});
						}
						if (options.animation.duration) {
							$letter.css({
								"animation-duration": options.animation.duration,
								"-webkit-animation-duration": options.animation.duration,
								"-moz-animation-duration": options.animation.duration,
								"-o-animation-duration": options.animation.duration
							});
						}

						var delay = (i + 1) * parseFloat(options.animation.spacing) + "s";
						$letter.css({
							"animation-delay": delay,
							"-webkit-animation-delay": delay,
							"-moz-animation-delay": delay,
							"-o-animation-delay": delay
						});

					}

					$main.append($letter);
				}
				if (options.animation && options.animation.spacing == 0) {
					$main.css({
						"animation-name": options.animation.name,
						"-webkit-animation-name": options.animation.name,
						"-moz-animation-name": options.animation.name,
						"-o-animation-name": options.animation.name
					});
					$main.css({
						"animation-duration": options.animation.duration,
						"-webkit-animation-duration": options.animation.duration,
						"-moz-animation-duration": options.animation.duration,
						"-o-animation-duration": options.animation.duration
					});
					$main.find(".letter-con").css("opacity", 1);
				}
				$(this).findfriend("playaudio", "render_audio");

				function bindevent() {
					// 开始拖动事件
					function handleDragStart(e) {
						if (!options.started) {
							if (!$(that).find(".action a").hasClass("shake")) {
								$(that).find(".action a").addClass("shake");
								setTimeout(function() {
									$(that).find(".action a").removeClass("shake")
								}, 1000);
							}
							return;
						}
						$(this).addClass("move");
						options.$drag = $(this);
					}
					//离开
					function handleDragLeave(e) {
						if (!options.started) {
							return;
						}
						options._isover = false;
						$(this).removeClass('over')
					}
					//经过
					function handleDragOver(e) {
						if (!options.started) {
							return;
						}
						if (!$(this).data("right")) {

							$(this).addClass('over');
							if (!options._isover) {
								$jq.findfriend("playaudio", "over_audio");
							}
							options._isover = true;
						}
						if (e.preventDefault) {
							e.preventDefault();
						}
						return false;
					}

					function handleDrop(e) {
						if (!options.started) {
							return;
						}
						var $taget = $(this);
						var $drag = options.$drag;
						if ($drag[0] != this && $taget.attr("draggable") === "true") {
							var draghtml = $drag.html();
							var dindex = $drag.data("index");
							$drag.html($taget.html());
							$drag.data("index", $taget.data("index"));
							$taget.html(draghtml);
							$taget.data("index", dindex);
							options.steep++;
							if (options.istimes) {
								$jq.find(".steep").html(options.steep);
							}
							$jq.findfriend("checkValue", $drag);
							$jq.findfriend("checkValue", $taget);
							options.onswitch($drag, $taget);
						}
						return false;
					}
					//结束事件
					function handleDragEnd(e) {
						if (!options.started) {
							return;
						}
						$(this).removeClass("move");
						$jq.find(".hanzi.over").removeClass("over");
					}
					$jq.find(".hanzi")
						.bind("dragstart", handleDragStart)
						.bind('dragover', handleDragOver)
						.bind('dragleave', handleDragLeave)
						.bind('drop', handleDrop)
						.bind('dragend', handleDragEnd);
				}

				function phoneevent() {
					function touchstart(e) {

						if (e.targetTouches.length == 1) { //单点触碰
							if (!options.started) {
								if (!$(that).find(".action a").hasClass("shake")) {
									$(that).find(".action a").addClass("shake");
									setTimeout(function() {
										$(that).find(".action a").removeClass("shake")
									}, 1000);
								}
								return;
							}
							var touch = event.targetTouches[0]; // 把元素放在手指所在的位置
							options.$drag = $(this);
							var _$drag = $(this).clone();
							options._$drag = _$drag;
							var offset = $(this).offset();
							var x = offset.left;
							var y = offset.top;
							$(this).data("start", {
								x: x,
								y: y
							});
							$(this).data("e_start", {
								x: touch.pageX,
								y: touch.pageY
							});
							$(this).parent().append(_$drag);
							_$drag.css({
								"position": "absolute",
								left: x,
								top: y,
								'z-index': '2'
							});
							$(this).addClass("move");
							_$drag.addClass("move");
						}
					}

					function touchmove(e) {
						if (!options.started) {
							return;
						}
						e.preventDefault(); //阻止其他事件
						if (e.targetTouches.length == 1) { //单点触碰
							var touch = event.targetTouches[0]; // 把元素放在手指所在的位置
							var start = $(this).data("start");
							var e_start = $(this).data("e_start");
							var _x = e_start.x - touch.pageX;
							var _y = e_start.y - touch.pageY;
							var x = start.x - _x;
							var y = start.y - _y;
							options._$drag.css({
								left: x,
								top: y
							});
							checkmove(touch.pageX, touch.pageY);
						}
					}

					function touchend(e) {
						if (!options.started) {
							return;
						}
						if (options.$taget) {
							var $drag = options.$drag;
							var $taget = options.$taget;
							var draghtml = $drag.html();
							var dindex = $drag.data("index");
							$drag.html($taget.html());
							$drag.data("index", $taget.data("index"));
							$taget.html(draghtml);
							$taget.data("index", dindex);
							options.steep++;
							if (options.istimes) {
								$jq.find(".steep").html(options.steep);
							}
							$jq.findfriend("checkValue", $drag);
							$jq.findfriend("checkValue", $taget);
							options.onswitch($drag, $taget);
							$drag.removeClass("move");
							$taget.removeClass("over");
							options._$drag.remove();
							delete options._$drag;
							delete options.$drag;
							delete options.$taget;
						} else {
							options._$drag.remove();
							options.$drag.removeClass("move");
							options.$taget.removeClass("over");
							delete options._$drag;
							delete options.$drag;
							delete options.$taget;
						}
					}

					function checkmove(x, y) {

						var c = $jq.find(".hanzi");
						var has = null;
						c.each(function() {
							if (!$(this).hasClass("right") && !$(this).hasClass("move")) {
								var offset = $(this).offset();
								var l = offset.left;
								var t = offset.top;
								var w = $(this).width();
								var h = $(this).height();
								var _x = x - l;
								var _y = y - t;
								if (_x > 0 && _x < w && _y > 0 && _y < h) {
									if (!$(this).hasClass("over")) {

										$(this).addClass("over");
										$jq.findfriend("playaudio", "over_audio");
									}
									has = $(this);

								} else {
									$(this).removeClass("over");
								}
							}
						});
						options.$taget = has;
					}
					$jq.find(".hanzi").each(function() {
						this.addEventListener('touchstart', touchstart, false);
						this.addEventListener('touchmove', touchmove, false);
						this.addEventListener('touchend', touchend, false);
					});

				}
				if ($.isPhone()) {
					phoneevent();
				} else {
					bindevent(); //绑定事件
				}
			});
		},
		//开始
		start: function(jq) {
			$(jq).each(function() {
				var options = $(this).findfriend("options");
				if (options.timer) {
					clearInterval(options.timer);
					options.timer = null;
				}
				options.time = 0;
				options.right = 0;
				options.steep = 0;
				options.onstart();
				options.started = true;
				var that = this;
				var $jq = $(this);
				options.timer = setInterval(function() { //开始记时
					options.time++;
					if (options.istimer) {
						$(that).find(".time").html(options.time);
					}
				}, 1000);
			});
		},
		//结束
		over: function(jq) {
			jq.each(function() {
				$(this).findfriend("playaudio", "success_audio");
				var options = $(this).findfriend("options");
				if (options.timer) {
					clearInterval(options.timer);
					options.timer = null;
				}

				function getStar() { //需要实际的计算方式
					return 5;
				}
				if (typeof options.onover == "function") {
					options.onover(getStar());
				} else if (typeof options.onover == "object") {
					options.onover.result = getStar();
					var dom = options.onover.render();
					if (dom) {
						$(this).append(dom);
					}
				}
			});
		},
		//检测某个汉字与拼音是否对应
		checkValue: function(jq, params) {
			var p = [];
			if (!$.isArray(params)) p = [params];
			var dom = params[0];
			var audio = params[1];
			$(jq).each(function() {
				var options = $(this).findfriend("options");
				var that = this;
				$(dom).each(function() {
					var index = $(this).data("index");
					var pindex = $(this).siblings(".pinyin").data("index");
					if (index == pindex) {
						//if(audio){
						$(that).findfriend("playaudio", "right_audio");
						//}
						$(this).data("right", true);
						$(this).addClass("right");
						$(this).attr("draggable", "false");
						options.right++;
						if (options.total == options.right) {
							$(that).findfriend("over");
						}
					}

				});
			});
		}
	});
})(jQuery);